package com.itheima.spring.beans;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 提前实例化单例Bean
 */
public class PreBuildBeanFactory extends DefaultBeanFactory {

    private final Log logger = LogFactory.getLog(getClass());
    private List<String> beanNames = new ArrayList<>();
    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionRegisterException {
        super.registerBeanDefinition(beanName, beanDefinition);
        synchronized (beanNames){
            beanNames.add(beanName);
        }
    }

    public void preInstantiateSingletons() throws Throwable{
        synchronized (beanNames){
            for(String beanName:beanNames){
                BeanDefinition bd = this.getBeanDefinition(beanName);
                if(bd.isSingleton()){
                    this.doGetBean(beanName);
                    if (logger.isDebugEnabled()) {
                        logger.debug("preInstantiate: name=" + beanName + " " + bd);
                    }
                }
            }
        }
    }
}
